package com.socket;

import java.io.DataInputStream;
import java.io.IOException;

public class RecThread implements Runnable {
    private DataInputStream dis;
    private byte[] head = new byte[8];
    private int headLen = 0;

    public RecThread(DataInputStream dis) {
        super();
        this.dis = dis;
    }

    public void run() {
        while (true) {
            try {//获取包头数据
                int len = dis.read(head, headLen, 8 - headLen);
                //判断包头数据是否完整
                headLen += len;//记录包头长度
                if (headLen == 8) {
                    int packetLen = head[1] << 8 | head[0];
                    System.out.println("包长度:" + packetLen);
                    headLen = 0;

                    //读取包体数据
                    byte[] body = new byte[packetLen];
                    int bodyLen = 0;
                    while (true) {
                        int recBodyLen = dis.read(body, bodyLen, packetLen - bodyLen - 8);
                        bodyLen += recBodyLen;
                        //得到完整包
                        if (bodyLen == (packetLen - 8)) {
                            //解析数据
                            UnPacket unPacket = new UnPacket(head, body);
                            unPacket.Parser();
                            break;
                        }
                    }
                } else {
                    System.out.println("包头不够继续接收");
                }
            } catch (IOException e) {
                break;
            }
        }
    }
}
